package snail.controllers;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.*;
import org.hibernate.Session;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import org.springframework.web.servlet.view.RedirectView;
import snail.data.ArticleDAO;
import snail.data.DAOFactory;
import snail.data.IUserDAO;
import snail.data.UserDAO;
import snail.hibernate.util.HibernateUtil;
import snail.misc.Hash;
import snail.misc.PreparedModelAndView;
import snail.model.Article;
import snail.model.User;

public class UserController extends MultiActionController {

    public UserController() {
    }

    public ModelAndView index(
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        ModelAndView mv = new PreparedModelAndView(request);
        return mv;
    }

    public ModelAndView watched(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new PreparedModelAndView("watched", request);
        return mv;
    }

    public ModelAndView logout(HttpServletRequest request, HttpServletResponse response) throws Exception {

        request.getSession().removeAttribute("user");

        return new PreparedModelAndView(new RedirectView("../"), request);

    }

    /*
     * Log in user
     */
    public ModelAndView login(HttpServletRequest request, HttpServletResponse response, Object returnTo) {

        ModelAndView mv = new PreparedModelAndView("/user/login", request);

        if (returnTo != null && returnTo instanceof String) {
            mv.addObject("pleaseLogin", "Var vänlig logga in för att kunna nå sidan.");
            mv.addObject("returnto", returnTo);
        }

        if (request.getMethod().equals("POST") && !(returnTo instanceof String)) {

            String email = request.getParameter("email");
            String password = Hash.sha256(request.getParameter("password"));
            User loggedInUser = new UserDAO().validateUser(email, password);

            if (loggedInUser != null) {
                if (loggedInUser.isConfirmed()) {
                    request.getSession().setAttribute("user", loggedInUser);
                    request.getSession().setAttribute("test", "text fran test");
                    String returnto = request.getParameter("returnto");
                    if (returnto != null && !returnto.equals("")) {
                        try {
                            response.sendRedirect(returnto);
                        } catch (IOException ex) {
                            Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    } else {
                        try {
                            response.sendRedirect("profile");
                        } catch (IOException ex) {
                            Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                } else {
                    mv.addObject("error", "Ditt konto är inte aktiverat.");
                }
            } else {
                String ERROR_CODE = "Fel användarnamn eller lösenord. Försök igen.";
                mv.addObject("error", ERROR_CODE);
            }
        }
        return mv;
    }

    public ModelAndView profile(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ModelAndView mv = new PreparedModelAndView(request);

        User user = ((User) request.getSession().getAttribute("user"));

        // if user not logged in -> redirect to login page
        if (user == null) {
            return login(request, response, "profile");
        }

        User u = (User) request.getSession().getAttribute("user");

        List<Article> l = new ArticleDAO().getAllExpired();
        List<Article> ret = new ArrayList<Article>();
        for (Article a : l) {
            if (a.getHighestBid() != null && a.getHighestBid().getUser().getUserId() == user.getUserId()) {
                ret.add(a);
            }
        }
        mv.addObject("wins", ret);

        mv.addObject("user", user);
        return mv;
    }

    public ModelAndView registerComplete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String registrationComplete = (String) request.getSession().getAttribute("registrationComplete");
        if (registrationComplete == null) {
            response.sendRedirect("../"); // redirect to start page if user
            // tries to reach it without first registred
        }
        request.getSession().removeAttribute("registrationComplete");
        return new PreparedModelAndView(request);
    }

    /**
     * The user will reach this page when he clicks the
     * verification link in the e-mail after registration.
     */
    public ModelAndView verify(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ModelAndView mv = new PreparedModelAndView("user/verify", request);

        String hash = request.getParameter("key");
        int userId = Integer.parseInt(request.getParameter("id"));

        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();

        DAOFactory daoFactory = DAOFactory.instance(DAOFactory.HIBERNATE);
        IUserDAO userDao = daoFactory.getUserDAO();
        User user = userDao.getById(userId);


        String email2hash = Hash.sha1(user.getEmail());

        if (user != null && hash.equals(email2hash)) {
            if (!user.isConfirmed()) {
                user.setConfirmed(true);
            }
        } else {
            response.sendRedirect("http://lmgtfy.com/?q=Vad+ska+jag+g%C3%B6ra+om+jag+har+fel+aktiveringskod%3F");
        }

        session.getTransaction().commit();
        return mv;
    }
}
